package kr.saeildamil.androidstudy_second.br_service;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;

public class MessengerServiceTest extends Activity implements OnClickListener{
	Messenger mService;
	boolean mBound;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch2930_messengerservicetest);
		findViewById(R.id.messengerservicetest_start).setOnClickListener(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if(mBound){
			unbindService(mConn);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		bindService(new Intent(this,MessengerService.class), mConn, Context.BIND_AUTO_CREATE);
	}
	
	private ServiceConnection mConn = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			mBound = false;
			
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
			mBound = true;
			
		}
	};
	
	@Override
	public void onClick(View v) {
		if(!mBound)return;
		Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO,0,0);
		try {
			mService.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}
